package com.application.followdroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class NewFollower extends Activity{

	private ProgressDialog load_newfollower;
	private ProgressDialog iagree;
	private ProgressDialog idisagree;
	private String result;
	public String friend;
	private ArrayList<String> query_myuser = new ArrayList<String>();
	public String deleteit;
	
	private boolean rotateok;
	private Intent login_follower;
	private String pkg;
	private String user;
	
	
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_follower);	  
		
		login_follower=getIntent();
	    pkg=getPackageName();
	    user=login_follower.getStringExtra(pkg+".user_logged");
	    
	    if(rotateok==false)
	    {
	    	update_newfollower();
	    }  
	}
	
		public void update_newfollower()
		{
			load_newfollower = ProgressDialog.show(this, "New follower", "Loading...", true,false);
		    
			new Thread(new Runnable() 
			{
			    public void run() 
			    {	
		        	//Username
		        	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		        	nameValuePairs.add(new BasicNameValuePair("myuser",user));
		        	InputStream is=null;
		        	
		        	//Faccio il post http
		        	try
		        	{
		        		HttpClient httpclient = new DefaultHttpClient();
		        	    HttpPost httppost = new HttpPost("http://followdroid.it/script/whowantfollowme.php");
		        	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        	    HttpResponse response = httpclient.execute(httppost);
		        	    HttpEntity entity = response.getEntity();
		        	    is = entity.getContent();
		        	
		        	    //Converte la risposta HTTP in string
		        		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		        	    StringBuilder sb = new StringBuilder();
		        	    String line = null;
		        	    while ((line = reader.readLine()) != null) 
		        	    {
		        	    	sb.append(line + "\n");
		        	    }
		        	    
		        	    is.close();
		        	    result=sb.toString();
		        	}
		        	catch(Exception e)
		        	{
		        		handlerLoad.sendEmptyMessage(2);
		        	}
		        	 
		        	//Metto insieme i dati JSON
		        	try
		        	{
		        	    JSONArray jArray = new JSONArray(result);
		        	    if(result!=null)
		        	    {
		        	    	for(int i=0;i<jArray.length();i++)
		        	    	{
		        	    		JSONObject json_data = jArray.getJSONObject(i);
		        	    		friend=json_data.getString("myuser");
		        	    		query_myuser.add(i,json_data.getString("myuser"));
		        	    	}
		        	    	handlerLoad.sendEmptyMessage(1);
		        	    }
		        	    else
		        	    {
		        	    	handlerLoad.sendEmptyMessage(0);
		        	    }
		        	}
		        	catch(JSONException e)
		        	{
		        		handlerLoad.sendEmptyMessage(0);
		        	}
			    }
			}).start();
		}
		
		//Riempie la ListView con i risultati della ricerca
		public void riempilista()
		{
			ListView lv = (ListView) findViewById(R.id.lv_newfriends);
	        ArrayList<Person> personList=new ArrayList<Person>();

	        Person people;
	        for(int i=0;i<query_myuser.size();i++)
	        {
	        	people=new Person(query_myuser.get(i),"New request!",R.drawable.listuser);
	        	personList.add(people);
	        }
	       
	        ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>();   
	        for(int i=0;i<personList.size();i++)
	        {
	             Person p=personList.get(i);
	             HashMap<String,Object> personMap=new HashMap<String, Object>();
	             personMap.put("image", p.getPhotoRes());
	             personMap.put("follow", p.getFollow());
	             personMap.put("name", p.getName());
	             data.add(personMap);
	        }
	       
	        String[] from={"image","follow","name"};
	        int[] to={R.id.personImage,R.id.personfollow,R.id.personName};
	        
	        SimpleAdapter adapter=new SimpleAdapter(
	                        getApplicationContext(),
	                        data,
	                        R.layout.listtview_custom,
	                        from,
	                        to);
	       
	        ((ListView)findViewById(R.id.lv_newfriends)).setAdapter(adapter);

	        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() 
	        {
		        public void onItemClick(AdapterView parent, View v,int position, long id)
		        {
		        	opzioniutente(position);
		        }
	        });
		}
		
		public void opzioniutente(final int a)
		{
			final CharSequence[] friends = {"I agree, follow me","I disagree, don't follow me"};
			AlertDialog.Builder builderfr = new AlertDialog.Builder(this);
	    	//builderfr.setTitle("My friends:");
			builderfr.setItems(friends, new DialogInterface.OnClickListener() {
	    		public void onClick(DialogInterface dialog, int item) {
	    	        if(friends[item]=="I agree, follow me")
	    	        {
	    	        	iagree = ProgressDialog.show(NewFollower.this, "Registering new follower", "Wait please...", true,false);
	    	        	
	    	        	new Thread(new Runnable() 
	    	    		{
	    	    		    public void run() 
	    	    		    {
			    	        	deleteit=query_myuser.get(a);
				    			if(deleteit != null)
				    			{
				    				//Username e password da inviare al web service
				    	    		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				    	    		nameValuePairs.add(new BasicNameValuePair("myuser",user));
				    	    		nameValuePairs.add(new BasicNameValuePair("follow",deleteit));
				    	    		InputStream is=null;
				    		
				    	    		//Faccio il post http
				            		try
				            		{
				            			HttpClient httpclient = new DefaultHttpClient();
				            			HttpPost httppost = new HttpPost("http://followdroid.it/script/iagreetofollow.php");
				            			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				            			HttpResponse response = httpclient.execute(httppost);
				            	    	HttpEntity entity = response.getEntity();
				            	    	is = entity.getContent();
				            	    	//diminuisco di 1 il nuovo dei nuovi follower
				            	    	SharedPreferences pref = getSharedPreferences("new_friends",MODE_PRIVATE);   
				            			int new_follower=pref.getInt("newfriends",0);
				            			new_follower=new_follower-1;
				            			getSharedPreferences("new_friends",MODE_PRIVATE)
				        		        .edit()
				        		        .putInt("newfriends",new_follower)
				        		        .commit();
				                        //refresh della lista
				            			query_myuser.remove(a);
				                        
				                        handler_agree.sendEmptyMessage(5);
				            	    	
				            		}
				            		catch(Exception e)
				            		{
				            			handler_agree.sendEmptyMessage(2);
				            		}       	
				    	    	}
				    	    	else
				    	    	{
				    	    		handler_agree.sendEmptyMessage(0);
				    	    	}
	    	    		   
	    	    		    } 
	    	    		    
	    	    		}).start();
	    	        }
	    	        if(friends[item]=="I disagree, don't follow me")
	    	        {
	    	        	idisagree = ProgressDialog.show(NewFollower.this, "Deleting new follower", "Wait please...", true,false);
	    	        	
	    	        	new Thread(new Runnable() 
	    	    		{
	    	    		    public void run() 
	    	    		    {
			    	        	deleteit=query_myuser.get(a);
				    			if(deleteit != null)
				    			{
				    				//Username e password da inviare al web service
				    	    		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				    	    		nameValuePairs.add(new BasicNameValuePair("myuser",user));
				    	    		nameValuePairs.add(new BasicNameValuePair("follow",deleteit));
				    	    		InputStream is=null;
				    		
				    	    		//Faccio il post http
				            		try
				            		{
				            			HttpClient httpclient = new DefaultHttpClient();
				            			HttpPost httppost = new HttpPost("http://followdroid.it/script/delete_whofollowme.php");
				            			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				            			HttpResponse response = httpclient.execute(httppost);
				            	    	HttpEntity entity = response.getEntity();
				            	    	is = entity.getContent();
				            	    	
				                        //refresh della lista
				            	    	query_myuser.remove(a);
				                        
				                        handler_disagree.sendEmptyMessage(1);
				            		}
				            		catch(Exception e)
				            		{
				            			handler_disagree.sendEmptyMessage(2);
				            		}       	
				    	    	}
				    	    	else
				    	    	{
				    	    		handler_disagree.sendEmptyMessage(1);
				    	    	}
			    	        }
	    	    		}).start();
	    	        }
	    	    }
	    	});
	    	AlertDialog viewtypefr = builderfr.create();
	    	viewtypefr.show();
		}	
	
		private Handler handlerLoad = new Handler() 
		{
			public void handleMessage(Message msg) 
			{
				load_newfollower.dismiss();
			    if (msg.what==1)
			    {
			    	Toast.makeText(NewFollower.this, "Your follower", Toast.LENGTH_SHORT).show();
			    	riempilista();
			    } 
			    if (msg.what==0) 
			    {
			    	Toast.makeText(NewFollower.this, "No one is following you...tell a friend to follow you!", Toast.LENGTH_LONG).show();
			    }
			    
			    if (msg.what==2)
			    {
			    	//Errore di connessione
			    	Toast.makeText(NewFollower.this, "Error! Please try again...", Toast.LENGTH_LONG).show();
			    }
			}
		};
		
		private Handler handler_agree = new Handler() 
		{
			public void handleMessage(Message msg) 
			{
				iagree.dismiss();
				if(msg.what==5)
			    {
			    	//Hai accettato la richiesta
			    	Toast.makeText(NewFollower.this, deleteit+" is your friend now!", Toast.LENGTH_LONG).show();
		            riempilista();
			    }
				if (msg.what==0) 
			    {
			    	Toast.makeText(NewFollower.this, "No one is following you...tell a friend to follow you!", Toast.LENGTH_LONG).show();
			    }
			    
			    if (msg.what==2)
			    {
			    	//Errore di conversione
			    	Toast.makeText(NewFollower.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
			    }
			}
		};
		
		private Handler handler_disagree = new Handler() 
		{
			public void handleMessage(Message msg) 
			{
				idisagree.dismiss();
				if(msg.what==0)
			    {
			    	//Non hai accettato la richiesta
			    	Toast.makeText(NewFollower.this, "You have deleted "+deleteit+" from your follower!", Toast.LENGTH_LONG).show();
		            riempilista();
			    }
				if (msg.what==1) 
			    {
			    	Toast.makeText(NewFollower.this, "No one is following you...tell a friend to follow you!", Toast.LENGTH_LONG).show();
			    	riempilista();
			    }
			    
			    if (msg.what==2)
			    {
			    	//Errore di conversione
			    	Toast.makeText(NewFollower.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
			    }
			}
		};
	
		@Override
		public boolean onCreateOptionsMenu(Menu menu)
		{
			super.onCreateOptionsMenu(menu);
			menu.add(0,0,1,"Refresh").setIcon(R.drawable.refresh);
			return true;
		}
		
		public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) 
			{
				//Refresh lista degli amici
				case 0:
					rotateok=false;
					query_myuser.removeAll(query_myuser);
					update_newfollower();
				break;
			}
			return false;
		}
		
		@Override
	    public void onConfigurationChanged(Configuration newConfig) 
		{
	        super.onConfigurationChanged(newConfig);
	        rotateok=true;
	    }
		
		@Override
		public void onBackPressed() 
		{
		    finish();
		    return;
		}
	}